package com.quasar.hpatient.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.custommodel.PhotoModel;
import com.quasar.hpatient.model.event.TestUpdatePhoto;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.event.UpdatePhoto;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.TestRecordData;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.OnPhotoListener;
import com.quasar.hpatient.presenter.ImagePresenter;
import com.quasar.hpatient.utils.FileUtils;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.view.adapter.ViewPagerAdapter;
import com.quasar.hpatient.view.record.TestRecordActivity;
import com.quasar.hpatient.widget.CustomFAB;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片查看界面
 */
@EActivity(R.layout.activity_image_viewpage)
public class ImageViewpageActivity extends BaseActivity implements OnPhotoListener {

    @Extra
    ArrayList<String> Photolist;
    @Extra
    int position;
    @ViewById(R.id.pager)
    ViewPager mPager;
    @ViewById(R.id.textsize)
    TextView textsize;
    @ViewById(R.id.cf_imageButton)
    CustomFAB cf_imageButton;
    @Extra
    String STATS;

    private List<ImageView> mList;
    private ViewPagerAdapter mviewPagerAdapter;
    private ImagePresenter imagePresenter;
    String uris;
    @Extra
    ArrayList<PhotoModel> photoModelDatas;

    @ViewById(R.id.iv_right2)
    TextView iv_right2;
    @ViewById(R.id.iv_right)//保存
            TextView iv_right;

    @AfterViews
    void init() {

        iv_right2.setText("编辑");
        iv_right.setText("保存图片");
        imagePresenter = new ImagePresenter(this);
        initView();
        initToolbar();
        initData();
        //传过来的图片集合
        int size = TestRecordActivity.picListBeen.size();


        if (STATS != null) {
            cf_imageButton.setVisibility(View.GONE);
            iv_right2.setVisibility(View.GONE);
            iv_right.setVisibility(View.GONE);
        } else {
            cf_imageButton.setVisibility(View.VISIBLE);
            iv_right2.setVisibility(View.VISIBLE);
            iv_right.setVisibility(View.VISIBLE);
        }

    }
    PhotoView view;
    @Override
    protected void initView() {

        mList = new ArrayList<ImageView>();

        for (int i = 0; i < Photolist.size(); i++) {
            view = new PhotoView(ImageViewpageActivity.this);
            view.enable();
            Glide.with(ImageViewpageActivity.this)
                    .load(Photolist.get(i))
                    .asBitmap()
                    .into(view);

            mList.add(view);
        }
    }

    int photo_position;

    @Override
    protected void initData() {

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        mviewPagerAdapter = new ViewPagerAdapter(mList);
        mPager.setAdapter(mviewPagerAdapter);

        if (position != 0) {
            mPager.setCurrentItem(position);
        }
        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {


                photo_position = position + 1;
                if (Photolist.size() != 0) {
                    textsize.setText(position + 1 + "/" + Photolist.size());
                }

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //保存图片
    @Click(R.id.iv_right)
    public void iv_right() {
        if (photo_position != 0) {
            for (int i = 0; i < Photolist.size(); i++) {
                uris = Photolist.get(photo_position - 1);
            }

            ViseLog.d("保存图片");
            //添加异常
            try {
                TestRecordData.PicListBean picListBean = TestRecordActivity.picListBeen.get(photo_position - 1);

                if (picListBean != null) {
                    ViseLog.d("保存图片+picListBean");
                    imagePresenter.GetImageUrls(uris);
                }
            } catch (Exception e) {
                msg("请先提交图片到服务器");
            }
        }
    }

    //编辑图片
    @Click(R.id.iv_right2)
    public void iv_right2() {
        if (photo_position != 0) {
            for (int i = 0; i < Photolist.size(); i++) {
                uris = Photolist.get(photo_position - 1);
            }

            //添加异常
            try {
                TestRecordData.PicListBean picListBean = TestRecordActivity.picListBeen.get(photo_position - 1);
                if (picListBean != null) {
                    EditImageActivity_.intent(this).imageUrls(uris).picListBean(picListBean).postion(photo_position - 1).start();
                } else {
                    EditImageActivity_.intent(this).imageUrls(uris).postion(photo_position - 1).start();
                }
            } catch (Exception e) {
                msg("请先提交图片到服务器");
            }
        }
    }

    //返回按钮
    @Click(R.id.ll_left)
    public void ll_left() {
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdatePhoto updatePhoto) {

//        if (updateEvent.type.equals(ConstantManger.ClosePhoto)) {
//            finish();
//        }

        if(updatePhoto.urlpath!=null){

            ViseLog.d("返回的下标"+updatePhoto.postion+"地址"+updatePhoto.urlpath);
            Photolist.set(updatePhoto.postion, RetrofitConnection.PHOTOURL+updatePhoto.urlpath);
            position=updatePhoto.postion;

            TestUpdatePhoto testUpdatePhoto=new TestUpdatePhoto();
            testUpdatePhoto.postion=updatePhoto.postion;
            testUpdatePhoto.urlpath=RetrofitConnection.PHOTOURL+updatePhoto.urlpath;
            EventBus.getDefault().post(testUpdatePhoto);
            initView();
            initData();
        }
    }

    //判断文件夹是否存在不存在则创建
    public void Exists() {
        String fenli = ConstantManger.IMAGEURLS;
        File fenlif = new File(fenli);
        if (!fenlif.exists()) {
            //若不存在，创建目录，可以在应用启动的时候创建
            fenlif.mkdirs();
            setTitle("paht ok,path:" + fenlif);
        }
    }


    //删除按钮
    @Click(R.id.cf_imageButton)
    public void cf_imageButton() {
        ViseLog.d("删除图片的id" + photo_position);
        if (photo_position != 0) {
            for (int i = 0; i < Photolist.size(); i++) {
                uris = Photolist.get(photo_position - 1);
            }

            //添加异常
            try {
                final TestRecordData.PicListBean picListBean = TestRecordActivity.picListBeen.get(photo_position - 1);
                if (picListBean != null) {
                    ViseLog.d("保存图片+picListBean");

                    SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                        @Override
                        public void onPositiveActionClicked(DialogFragment fragment) {
                            super.onPositiveActionClicked(fragment);
                            showDialog();
                            //删除网络图片
                            if (StringUtils.isImgUrl(picListBean.getCover())) {
                                ViseLog.d("删除网络图片" + picListBean.getCover());
                                //删除网络图片
                                imagePresenter.deletePhoto(picListBean.getId() + "");
                            }
                        }

                        @Override
                        public void onNegativeActionClicked(DialogFragment fragment) {
                            super.onNegativeActionClicked(fragment);
                        }
                    };
                    builder.title("确定删除化验图片？").positiveAction("删除").negativeAction("取消");
                    ((SimpleDialog.Builder) builder).message("注：图片可提高医生对化验单做出的诊断(删除网络图片后本地图片需要重新选取)");
                    DialogFragment fragment = DialogFragment.newInstance(builder);
                    fragment.show(getSupportFragmentManager(), null);
                }
            } catch (Exception e) {
                //删除本地图片
                SimpleDialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
                    @Override
                    public void onPositiveActionClicked(DialogFragment fragment) {
                        super.onPositiveActionClicked(fragment);
                        String index = textsize.getText().toString();
                        if (index.indexOf("/") != -1) {
                            String[] strs = index.split("/");
                            //ViseLog.d("删除的化验单图片"+ photoModelDatas.get(Integer.parseInt(strs[0])-1).getOriginalPath());
                            ViseLog.d("删除本地图片" + TestRecordActivity.minitDatas.get(Integer.parseInt(strs[0]) - 1).getOriginalPath());
                            TestRecordActivity.minitDatas.remove(Integer.parseInt(strs[0]) - 1);
                            TestRecordActivity.notifyDataSetChanged();
                            TestRecordActivity.photos.remove(Integer.parseInt(strs[0]) - 1);
                            mviewPagerAdapter.notifyDataSetChanged();
                            finish();
                        }

                    }

                    @Override
                    public void onNegativeActionClicked(DialogFragment fragment) {
                        super.onNegativeActionClicked(fragment);
                    }
                };
                builder.title("确定删除化验图片？").positiveAction("删除").negativeAction("取消");
                ((SimpleDialog.Builder) builder).message("注：图片可提高医生对化验单做出的诊断");
                DialogFragment fragment = DialogFragment.newInstance(builder);
                fragment.show(getSupportFragmentManager(), null);
            }
        }
    }

    @Override
    public void onViewSuccess(Bitmap data) {
        if (data != null) {
            Exists();  //
            String name=ConstantManger.IMAGENAME;
            FileUtils.SavePic(data, ConstantManger.IMAGEURLS,name);
            ViseLog.d(ConstantManger.IMAGEURLS + ConstantManger.IMAGENAME);
            // 发送广播
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/Yizhi/image/" + name))));
            //image.setImageBitmap(bitmap);
            msg("已经保存相册");
        }
    }

    @Override
    public void onViewError(String msg) {

        if (msg != null) {
            msg(msg);
        }
    }

    @Override
    public void onViewRefreshUI() {

    }

    //删除图片成功后
    @Override
    public void onDeletePtoto(DataStateResult dataStateResult) {
        if (dataStateResult.getMsgCode().equals("0x00000000")) {
            if (pd != null) {
                pd.dismiss();
            }
            //网络图片删除后删除viewPager里面的图片再对ViewPager进行刷新
            String index = textsize.getText().toString();
            if (index.indexOf("/") != -1) {
                String[] strs = index.split("/");
                //ViseLog.d("删除的化验单图片"+ photoModelDatas.get(Integer.parseInt(strs[0])-1).getOriginalPath());
                ViseLog.d("删除本地图片" + TestRecordActivity.minitDatas.get(Integer.parseInt(strs[0]) - 1).getOriginalPath());
                TestRecordActivity.minitDatas.remove(Integer.parseInt(strs[0]) - 1);
                TestRecordActivity.photos.remove(Integer.parseInt(strs[0]) - 1);
                TestRecordActivity.picListBeen.remove(Integer.parseInt(strs[0]) - 1);
                TestRecordActivity.notifyDataSetChanged();
                mviewPagerAdapter.notifyDataSetChanged();
                finish();
            }
        }
    }

}